package com.szqhyxj.youxiangju.sys.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.webkit.MimeTypeMap;

import com.yanzhenjie.permission.FileProvider;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * XiaoPanYu
 * on 2018/11/12
 */
public class ApkUtil {

    /**
     * 打开APK程序代码
     *
     * @param file    apk 路径
     * @param context
     */
    public static void openAppFile(File file, Context context) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static void openFile(File file, Context context) {
        Intent var2 = new Intent();
        var2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        var2.setAction(Intent.ACTION_VIEW);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
            Uri uriForFile = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
            var2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            var2.setDataAndType(uriForFile, context.getContentResolver().getType(uriForFile));
        }else{
            var2.setDataAndType(Uri.fromFile(file), getMIMEType(file));
        }
    }
    public static String getMIMEType(File var0) {
        String var1 = "";
        String var2 = var0.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }

    /**
     * 获取app系统路径
     *
     * @param context
     * @return
     */
    public static File getAppSystemPath(Context context) {

        File apkFile = new File(Environment.getExternalStorageDirectory(), "youxiangju.apk");
        return apkFile;
    }


    //将下载的文件写入本地存储
    public static void writeFile2Disk(Response<ResponseBody> response, File file, DownloadListener downloadListener) {
        downloadListener.onStart();
        long currentLength = 0;
        OutputStream os = null;
        InputStream is = response.body().byteStream();
        File apkFile = new File(file, "youxianju.apk");
        //获取下载输入流
        long totalLength = response.body().contentLength();
        try {
            os = new FileOutputStream(apkFile);
            //输出流
            int len;
            byte[] buff = new byte[1024];
            while ((len = is.read(buff)) != -1) {
                os.write(buff, 0, len);
                currentLength += len;
                Log.e("writeFile2Disk", totalLength + "当前进度: " + currentLength);
                //计算当前下载百分比，并经由回调传出
                downloadListener.onProgress(totalLength, currentLength);
                //当百分比为100时下载结束，调用结束回调，并传出下载后的本地路径
                if ((currentLength >= totalLength)) {
                    downloadListener.onFinish(apkFile.getPath());
                    //下载完成
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                    //关闭输出流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                    //关闭输入流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public interface DownloadListener {
        void onStart();

        void onProgress(long totalBytes, long soFarBytes);

        void onFinish(String localPath);

        void onFailure();
    }

}
